package com.lisx.module_time_block.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ToastUtils;
import com.fenghuajueli.lib_data.constants.EventBusConstants;
import com.fenghuajueli.lib_data.entity.db.DayPlanDbEntity;
import com.fenghuajueli.lib_data.entity.db.MonthPlanDbEntity;
import com.fenghuajueli.lib_data.entity.db.WeekPlanDbEntity;
import com.fenghuajueli.lib_data.entity.eventbus.EventEntity;
import com.fenghuajueli.libbasecoreui.manager.TimeBlockManager;
import com.fenghuajueli.libbasecoreui.mvp.BaseActivity;
import com.fenghuajueli.libbasecoreui.utils.MyStatusBarUtils;
import com.lisx.module_time_block.R;
import com.lisx.module_time_block.databinding.ActivityMonthBlockDetailsBinding;
import com.lisx.module_time_block.dialogfragment.DakaDialogFragment;
import com.lisx.module_time_block.utils.TimeUtils;
import com.necer.calendar.BaseCalendar;
import com.necer.enumeration.CheckModel;
import com.necer.enumeration.DateChangeBehavior;
import com.necer.listener.OnCalendarChangedListener;
import com.necer.painter.InnerPainter;

import org.greenrobot.eventbus.EventBus;
import org.joda.time.LocalDate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MonthBlockDetailsActivity extends BaseActivity {

    private int position;
    private DayPlanDbEntity dayPlanDbEntity;
    private ActivityMonthBlockDetailsBinding binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMonthBlockDetailsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        MyStatusBarUtils.setStatusBar(this,"#5AB4C7");

        position = getIntent().getIntExtra("position", 0);
        int currentMonthLastDay = TimeUtils.getCurrentMonthLastDay();
        binding.tvJihua.setText("计划打卡" + currentMonthLastDay + "天");
        binding.progress.setMax(currentMonthLastDay);
        binding.ivFanhui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        binding.tvDaka.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dayPlanDbEntity != null) {
                    DakaDialogFragment fragment = new DakaDialogFragment();
                    fragment.setData(dayPlanDbEntity);
                    fragment.setOnDakaListener(new DakaDialogFragment.OnDakaListener() {
                        @Override
                        public void onDaka(String msg) {
                            daka(dayPlanDbEntity, msg);
                        }
                    });
                    fragment.show(getSupportFragmentManager());
                }
            }
        });
        binding.monthCalendar.setCheckMode(CheckModel.SINGLE_DEFAULT_UNCHECKED);
        binding.monthCalendar.setOnCalendarChangedListener(new OnCalendarChangedListener() {
            @Override
            public void onCalendarChange(BaseCalendar baseCalendar, int year, int month, LocalDate localDate, DateChangeBehavior dateChangeBehavior) {
                binding.tvDate.setText(month + "月" + year);
            }
        });

        setData();

    }

    private void daka(DayPlanDbEntity entity, String msg) {
        long dakaTime = entity.getDaka_time();
        long currentTime = System.currentTimeMillis();
        if (!TimeUtils.isSameDay(dakaTime, currentTime, TimeZone.getDefault())) {
            if (TextUtils.isEmpty(msg)) {
                ToastUtils.showShort("请输入内容!");
                return;
            }
            update(entity, msg);
        } else {
            ToastUtils.showShort("今天已经打过卡了,明天再来噢!");
        }
    }

    private void update(DayPlanDbEntity dayPlanDbEntity, String msg) {
        MonthPlanDbEntity monthPlanDbEntity = new MonthPlanDbEntity();
        monthPlanDbEntity.setCreate_time(dayPlanDbEntity.getCreate_time());
        monthPlanDbEntity.setDaka_time(System.currentTimeMillis());
        monthPlanDbEntity.setDate(TimeUtils.getDate());

        if (dayPlanDbEntity.getDaka_count() == TimeUtils.getCurrentMonthLastDay()) {
            dayPlanDbEntity.setDaka_count(0);
        }
        dayPlanDbEntity.setDaka_count(dayPlanDbEntity.getDaka_count() + 1);
        dayPlanDbEntity.setDaka_time(System.currentTimeMillis());
        dayPlanDbEntity.setMsg(msg);
        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Boolean> emitter) throws Exception {
                TimeBlockManager.getInstance().updateDayPlan(dayPlanDbEntity);
                TimeBlockManager.getInstance().saveMonthPlanDbEntity(monthPlanDbEntity);
                emitter.onNext(true);
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull Boolean aBoolean) {
                        EventBus.getDefault().post(new EventEntity(EventBusConstants.SAVE_PLAN));
                        getMonthPlanData();
                        ToastUtils.showShort("打卡成功");
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        ToastUtils.showShort("打卡失败");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void setData() {
        Observable.create(new ObservableOnSubscribe<List<DayPlanDbEntity>>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<List<DayPlanDbEntity>> emitter) throws Exception {
                List<DayPlanDbEntity> dayPlanData = TimeBlockManager.getInstance().getDayPlanData(5);
                emitter.onNext(dayPlanData);
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<List<DayPlanDbEntity>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull List<DayPlanDbEntity> dayPlanDbEntities) {
                        if (dayPlanDbEntities != null) {
                            dayPlanDbEntity = dayPlanDbEntities.get(position);
                            binding.tvName.setText(dayPlanDbEntity.getPlan_name());
                            getMonthPlanData();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getMonthPlanData() {
        Observable.create(new ObservableOnSubscribe<List<MonthPlanDbEntity>>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<List<MonthPlanDbEntity>> emitter) throws Exception {
                List<MonthPlanDbEntity> monthPlanData = TimeBlockManager.getInstance().getMonthPlanData(dayPlanDbEntity.getCreate_time());
                emitter.onNext(monthPlanData);
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<List<MonthPlanDbEntity>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull List<MonthPlanDbEntity> monthPlanDbEntities) {
                        if (monthPlanDbEntities != null) {
                            binding.tvCount.setText("实际打卡" + monthPlanDbEntities.size() + "天");
                            binding.progress.setProgress(monthPlanDbEntities.size());
                            setTag(monthPlanDbEntities);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void setTag(List<MonthPlanDbEntity> monthPlanDbEntities) {
        List<String> pointList = new ArrayList<>();
        for (MonthPlanDbEntity monthPlanDbEntity : monthPlanDbEntities) {
            long dakaTime = monthPlanDbEntity.getDaka_time();
            pointList.add(TimeUtils.getDate(dakaTime));
        }
        InnerPainter innerPainter = (InnerPainter) binding.monthCalendar.getCalendarPainter();
        innerPainter.setPointList(pointList);
    }
}
